/*
 * author      : dormi330
 * date        : 2018/6/26
 * description : 订单删除
 */

package com.deep.trade.application.order;

import com.deep.trade.adaptor.required.member.Member;
import com.deep.trade.adaptor.required.member.MemberService;
import com.deep.trade.common.CommonUtils;
import com.deep.trade.common.TradeException;
import com.deep.trade.domain.order.OrderQueryRepository;
import com.deep.trade.domain.order.OrderRepository;
import com.deep.trade.domain.order.TradeOrder;
import com.deep.trade.order.dto.InDtoCancelOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderDeleteService {
    private static final int ONLY_ONE_SHOULD_BE_UPDATED = 1;
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    private OrderRepository orderRepository;
    private MemberService memberService;
    private OrderQueryService orderQueryService;

    @Autowired
    public OrderDeleteService(OrderRepository orderRepository
            , MemberService memberService
            , OrderQueryService orderQueryService
    ) {
        this.orderRepository = orderRepository;
        this.memberService = memberService;
        this.orderQueryService = orderQueryService;
    }


    /**
     * 删除一个订单
     *
     * @param inDtoCancelOrder 入参
     */
    @Transactional
    public void deleteTradeOrder(InDtoCancelOrder inDtoCancelOrder) throws Exception {
        logger.info("{}, {}", CommonUtils.currentClassAndMethod(), inDtoCancelOrder);

        if (null == inDtoCancelOrder) throw new TradeException("arguments cannot be null");

        String tradeOrderId = inDtoCancelOrder.getTradeOrderId();
        if (null == tradeOrderId) throw new TradeException("tradeOrderId cannot be null");

        TradeOrder tradeOrder = orderQueryService.assureTradeOrder(tradeOrderId);

        // TODO 删除权限校验
        Member member = memberService.memberOfToken();
        if (!tradeOrder.getMemberId().equals(member.getId())) {
            throw new TradeException("no priviledge to delete this order");
        }
        // ====== 领域对象操作 =======
        tradeOrder.delete();

        // ====== 存储 =======
        if (ONLY_ONE_SHOULD_BE_UPDATED != orderRepository.deleteTradeOrder(tradeOrder)) {
            throw new TradeException("audit fail, cannot get order to audit");
        }
    }
}
